package com.lqb.webScaffold.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import com.lqb.webScaffold.entity.Messages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket类
 *
 * @ServerEndpoint: socket链接地址
 */

@ServerEndpoint("/websocket/{userid}")
@Controller
@Component
public class UserMessageController {

    /**
     * 设置在线人数为静态变量
     */
    public static int onlineNumber = 0;

    /**
     * map(username,websocket)作为对象添加到集合中
     */
    private static Map<String, UserMessageController> clients = new ConcurrentHashMap<>();//用户

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * session会话
     */
    private Session session;

    /**
     * 用户ID
     */
    private String userId;

    /**
     * 监听连接（有用户连接，立马到来执行这个方法）
     * session 发生变化
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("userid") String userId, Session session) throws IOException {
        //每打开一个新的窗口，在线人数onlineNumber++
        onlineNumber++;
        this.userId = userId;
        this.session = session;
        logger.info("现在来连接的用户id：" + userId);
        logger.info("当前在线人数" + onlineNumber);
        clients.put(this.userId, this);
    }

    /**
     * 监听连接断开（有用户退出，会立马到来执行这个方法）
     */
    @OnClose
    public void onClose() throws CloneNotSupportedException {
        onlineNumber--;
        logger.info("有用户断开连接 用户id：" + userId);
        logger.info("当前在线人数" + onlineNumber);
        clients.remove(userId);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.info("服务端发生了错误" + error.getMessage());
    }

    /**
     * 监听消息（收到客户端的消息立即执行）
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            JSONObject jsonObject = new JSONObject(message);
            Messages messageAO = new Messages();
            messageAO.setFromUserId(jsonObject.getStr("fromUserId"));
            messageAO.setToUserId(jsonObject.getStr("toUserId"));
            messageAO.setContent(jsonObject.getStr("content"));
            messageAO.setImage(jsonObject.getStr("image"));
            messageAO.setMsgType(jsonObject.getInt("msgType"));
            messageAO.setCreateTime(new DateTime());
            if (messageAO.getToUserId().equals("all")) {
                sendMessageAll(messageAO);
            } else {
                sendMessageTo(messageAO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("发生了错误了");
        }
    }

    /**
     * 消息发送指定人
     */
    public void sendMessageTo(Messages message) throws IOException {
        for (UserMessageController item : clients.values()) {
            if (item.userId.equals(message.getToUserId())) {
                JSONObject jsonObject = new JSONObject(message);
                item.session.getBasicRemote().sendText(jsonObject.toString());
                break;
            }
        }
    }

    /**
     * 消息发送所有人
     */
    public void sendMessageAll(Messages message) throws IOException {
        for (UserMessageController item : clients.values()) {
            item.session.getBasicRemote().sendText(message.toString());
        }
    }
}
